<template>
  <!-- page_pet_care页面 -->
  <van-pull-refresh
    v-model="loading"
    success-text="刷新成功"
    @refresh="onRefresh"
  >
    <div class="page_pet_care">
      <header>
        <div class="header_city" @click="showFn('select_location')">
          <p>Select Location</p>
          <span></span>
        </div>
        <div class="header_list">
          <div
            class="header_list_item"
            v-for="(item, index) in petCareAll"
            :key="index"
            :class="{ active: petCareAllindex === index }"
            @click="petCareAllindex = index"
            :style="{ background: item.petCareAll_background }"
          >
            <img :src="item.petCareAll_img" alt="" />
            <span>{{ item.title }}</span>
          </div>
        </div>
      </header>
      <main>
        <!-- 下拉菜单 -->
        <AsyncOrderByDistance></AsyncOrderByDistance>
        <!-- 插槽 -->
        <div class="main_map">
          <img src="@/assets/Petcare-img/map.png" alt="" />

          <van-button round type="primary" color="#1ab692"
            >Find The Nearest Pet Store</van-button
          >

          <van-button
            @click="showFn('zip_code')"
            class="enter_zip_code"
            round
            type="success"
            >Enter zip code</van-button
          >
        </div>
      </main>
      <!-- 占位 -->
      <footer></footer>
    </div>
  </van-pull-refresh>
  <!-- enter zip code  弹窗 -->
  <van-popup
    class="MyPopup"
    v-model:show="show"
    closeable
    @close="inputValue = ''"
    position="bottom"
    round
    :style="{ height: '85%' }"
  >
    <!-- 固定头部区域 -->
    <div class="van_popup_header_sticky">
      <!-- 标题 -->
      <div class="van_popup__title">
        <h3 v-if="popupType === 'zip_code'">Enter zip code</h3>
        <h3 v-else>Select Location</h3>
      </div>

      <!-- 输入框 -->
      <div class="van_popup__content">
        <van-field
          type="text"
          ref="inputField"
          autosize
          v-model="inputValue"
          :placeholder="popupType === 'zip_code' ? 'zip code' : 'Search'"
          :style="{
            border:
              popupType === 'zip_code' ? '1px solid #1ab692' : '1px solid #ccc',
          }"
        >
          <!-- 自定义右侧图标 -->
          <template #right-icon>
            <van-icon
              @click="SearchFn"
              v-if="popupType !== 'zip_code'"
              class="iconfont icon-serach"
            />
          </template>
        </van-field>
      </div>

      <div v-show="popupType !== 'zip_code'" class="tags-container">
        <div class="tag">Toronto</div>
        <div class="tag">Vancouver</div>
        <div class="tag">Ottawa</div>
        <div class="tag">Montreal</div>
        <div class="tag">Calgary</div>
        <div class="tag">Quebec City</div>
      </div>
    </div>
    <!-- 按钮 -->
    <div v-if="popupType === 'zip_code'" class="van_popup__confirm" style="">
      <van-button @click="SubmitFn" round color="#1ab692" type="success"
        >Submit</van-button
      >
    </div>
    <!-- 可滚动的城市列表 -->
    <div v-else class="scroll-section">
      <van-index-bar
        ref="indexBarRef"
        :index-list="indexList"
        v-show="popupType !== 'zip_code'"
      >
        <!-- 循环渲染城市数据 -->
        <template v-for="(item, index) in cityData" :key="index">
          <van-index-anchor :index="index" />
          <van-cell
            v-for="city in item"
            :key="city"
            :title="city"
            @click="selectCity(city)"
            :style="{ color: ev === city ? '#18af90' : '#000' }"
            :class="{ selected: ev === city }"
          />
        </template>
      </van-index-bar>
    </div>
  </van-popup>
</template>

<script setup>
import { ref, nextTick, watch,defineAsyncComponent } from "vue";
import { pinyin } from "pinyin-pro";
import { debounce } from "lodash-es";

// 静态图片
import petcare_img1 from "@/assets/Petcare-img/petcare-img1.png";
import petcare_img2 from "@/assets/Petcare-img/petcare-img2.png";
import petcare_img3 from "@/assets/Petcare-img/petcare-img3.png";
import petcare_img4 from "@/assets/Petcare-img/petcare-img4.png";
import petcare_img5 from "@/assets/Petcare-img/petcare-img5.png";
import petcare_img6 from "@/assets/Petcare-img/petcare-img6.png";
import petcare_img7 from "@/assets/Petcare-img/petcare-img7.png";
import petcare_img8 from "@/assets/Petcare-img/petcare-img8.png";

// (1) 页面数据刷新逻辑
// 刷新逻辑响应式变量 loading加载
const loading = ref(false);
const onRefresh = () => {
  loading.value = true; // 开始刷新
  setTimeout(() => {
    loading.value = false; // 刷新完成
  }, 1000);
};

// (2)  select location + zip code 弹窗逻辑
const show = ref(false); // 弹窗显示状态
const popupType = ref(null);
const showFn = (type) => {
  popupType.value = type;
  show.value = true;
  nextTick(() => {
    if (inputField.value) {
      inputField.value.focus();
    }
  });
};
// (3) 头部城市列表
// 明确声明 props
const props = defineProps({
  defaultTab: {
    type: Number,
    default: 0,
  },
});

// 使用路由参数初始化 activeIndex
const petCareAllindex = ref(props.defaultTab);

const petCareAll = [
  {
    petCareAll_img: petcare_img1,
    title: "All",
    petCareAll_background: "linear-gradient(#aaf1e9 0%, white 90%)",
  },
  {
    petCareAll_img: petcare_img2,
    title: "Pet Hospital",
    petCareAll_background: "linear-gradient(to bottom, #dce2f5 0%, white 90%)",
  },
  {
    petCareAll_img: petcare_img3,
    title: "Boarding",
    petCareAll_background: "linear-gradient(to bottom, #ffece5 0%, white 90%)",
  },
  {
    petCareAll_img: petcare_img4,
    title: "Sitting",
    petCareAll_background: "linear-gradient(to bottom, #dcedfe 0%, white 90%)",
  },
  {
    petCareAll_img: petcare_img5,
    title: "Drop-ins",
    petCareAll_background: "linear-gradient(to bottom, #eee9ff 0%, white 90%)",
  },
  {
    petCareAll_img: petcare_img6,
    title: "Gromming",
    petCareAll_background: "linear-gradient(to bottom, #fff1cd 0%, white 90%)",
  },
  {
    petCareAll_img: petcare_img7,
    title: "Excursion",
    petCareAll_background: "linear-gradient(to bottom, #ecfbba 0%, white 90%)",
  },
  {
    petCareAll_img: petcare_img8,
    title: "Photography",
    petCareAll_background: "linear-gradient(to bottom, #e1e8f8 0%, white 90%)",
  },
];

// (4) Order By Distance 下拉菜单数据
const AsyncOrderByDistance = defineAsyncComponent(()=>import('@/components/OrderByDistance.vue'))

// (5)van-popup 数据
const inputValue = ref(""); // 输入框内容
const inputField = ref(null); //输入框实例
const indexBarRef = ref(null); //城市列表实例
// 城市数据
const cityData = {
  A: ["鞍山", "安顺"],
  B: ["北京", "保定", "包头"],
  C: ["长春", "重庆"],
  G: ["广东", "广州"],
  H: ["杭州", "海南"],
  W: ["武汉", "乌鲁木齐"],
  X: ["厦门", "西安"],
  Y: ["烟台", "银川"],
  Z: ["郑州", "中山"],
};
// 动态生成索引字母列表（仅包含有数据的字母）
const indexList = Object.keys(cityData); //获取所有字母 右侧对应左侧字母数量
// 选中的城市
const ev = ref(null);
// 点击城市事件
const selectCity = (city) => {
  ev.value = city;
  setTimeout(() => {
    show.value = false;
  }, 1000);
};

const scrollToMatchedLetter = debounce((inputText) => {
  try {
    // 清空时重置状态
    if (!inputText?.trim()) {
      nextTick(() => {
        document.querySelector(".scroll-section")?.scrollTo(0, 0);
      });
      return;
    }

    if (popupType.value !== "select_location") return;

    const firstChar = inputText.trim()[0];
    if (!firstChar) return;

    let targetLetter = "";

    // 处理中英文输入
    if (/[a-zA-Z]/.test(firstChar)) {
      targetLetter = firstChar.toUpperCase();
    } else if (/[\u4e00-\u9fa5]/.test(firstChar)) {
      const pinyinResult = pinyin(firstChar, {
        pattern: "first",
        toneType: "none",
        nonZh: "consecutive",
      });
      targetLetter = (pinyinResult || "").toUpperCase().charAt(0);
    }

    // 执行滚动定位
    if (targetLetter && indexList.includes(targetLetter)) {
      nextTick(() => {
        indexBarRef.value?.scrollTo(targetLetter);
      });
    }
  } catch (e) {
    console.error("匹配失败:", e);
  }
}, 300);
// 添加这行声明
watch(inputValue, (newVal) => {
  scrollToMatchedLetter(newVal);
});
const SearchFn = () => {
  // 立即执行搜索（跳过防抖）
  scrollToMatchedLetter.flush();
};
const SubmitFn = () => {
  // 提交按钮逻辑
  console.log(inputValue.value);
};
</script>

<style lang="scss">
.page_pet_care {
  height: 100vh;
  display: flex;
  flex-direction: column;
  header {
    height: 120px;
    background-color: rgba(174, 247, 242, 0.8);
    display: flex;
    flex-direction: column;
    justify-content: center;
    padding-left: 10px;
    .header_city {
      width: 128px;
      height: 30px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 16px;
      font-weight: bold;
      white-space: nowrap;

      // 小黑箭头
      span {
        border-top: 4px solid transparent;
        border-bottom: 4px solid transparent;
        border-right: 4px solid #000;
        transform: rotate(-90deg);
      }
    }
    .header_list {
      margin-top: 15px;

      display: flex;
      align-items: center;
      overflow-x: auto;
      scrollbar-width: none; /* 针对 Firefox 浏览器隐藏滚动条 */
      -ms-overflow-style: none; /* 针对 IE/Edge 浏览器隐藏滚动条 */

      &::-webkit-scrollbar {
        display: none; /* 针对 Chrome/Safari/Opera 浏览器隐藏滚动条 */
      }
      .header_list_item {
        border-radius: 10px;
        margin-left: 4px;
        white-space: nowrap;
        display: flex;
        align-items: center;
        padding: 6px 12px;
        span {
          font-size: 12px;
          font-weight: bold;
        }
        img {
          width: 20px;
          height: 20px;
          margin-right: 5px;
          vertical-align: middle;
          border-radius: 5px;
        }
        &:first-child {
          margin-left: 0;
        }
        &.active {
          background: linear-gradient(#aaf1e9 0%, white 90%);
          border: 2px solid #1bb593;
        }
      }
    }
  }
  main {
    position: relative;
    border-top-left-radius: 15px;
    border-top-right-radius: 15px;
    margin-top: -10px;
    background-color: #f7f7f7;
    overflow: hidden;
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    // 下拉菜单样式

    .main_map {
      display: flex;
      justify-content: center;
      align-items: center;
      display: flex;
      flex-direction: column;
      img {
        width: 150px;
        height: 150px;
        border-radius: 50%;
      }
      button {
        font-weight: bold;
        width: 240px;
        display: flex;
        justify-content: center;
        align-items: center;
        font-size: 14px;
        color: #000;
        border: 0;
        background-color: #e5e7eb;
        margin-top: 25px;
        &.enter_zip_code {
          margin-top: 10px;
        }
      }
    }
  }
  footer {
    height: 70px;
  }
}
.MyPopup {
  display: flex;
  flex-direction: column;
  /* 固定头部区域 */
  .van_popup_header_sticky {
    position: sticky;
    top: 0;
    z-index: 1;
    margin-bottom: 20px;
    .van_popup__title {
      height: 45px;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .van_popup__content {
      padding: 0 16px;
      .van-field {
        border-radius: 5px;
        .icon-serach {
          color: #545a64;
          font-weight: bold;
        }
      }
    }
    .tags-container {
      width: 90%;
      display: flex;
      flex-wrap: wrap;
      padding: 10px 16px 0;

      gap: 10px; /* 元素间距 */
      .tag {
        background-color: #f1f4f5; /* 背景颜色 */
        padding: 4px 10px; /* 内边距 */
        max-height: 29px;
        border-radius: 20px; /* 圆角 */
        font-size: 14px; /* 字体大小 */
        display: flex;
        justify-content: center;
        align-items: center;
        white-space: nowrap; /* 避免文字换行 */
      }
    }
  }
  // 按钮
  .van_popup__confirm {
    display: flex;
    justify-content: space-around;
    padding: 16px;
    button {
      width: 100%;
      font-size: 16px;
      font-weight: bold;
    }
  }
  /* 可滚动的城市列表 */
  .scroll-section {
    flex: 1;
    overflow-y: auto;
    margin-top: 10px;
    min-height: 0; /* 防止 flex 子项溢出 */
    padding-bottom: 250px;
    &::-webkit-scrollbar {
      display: none;
    }

    .van-index-bar {
      margin-top: 10px;
      .van-index-anchor {
        background-color: #f3f3f5;
      }
      .van-cell {
        position: relative;
        &::before {
          // 打对钩的样式
          content: "";
          position: absolute;
          top: 50%;
          right: 30px;
          width: 5px;
          height: 10px;
          border: 2px solid #18af90;
          border-left: 0;
          border-top: 0;
          transform: translateY(-50%) rotate(45deg);
          transition: opacity 0.3s; // 添加过渡效果
          opacity: 0; // 默认不显示
        }
        &.selected::before {
          opacity: 1; /* 选中时显示 */
        }
      }
      .van-index-bar__sidebar {
        top: 50%;
        transform: none;
        margin-right: 6px;
        .van-index-bar__index {
          font-size: 14px;
          padding: 2px;
          margin-top: 6px;
          &.van-index-bar__index--active {
            color: #fff;
            background-color: #18b88f;
            border-radius: 50%;
          }
        }
      }
    }
  }
}
</style>